package com.mes.cloud.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mes.cloud.api.dto.request.area.MarketDevelopmentPageRequest;
import com.mes.cloud.api.dto.request.area.MarketDevelopmentRequest;
import com.mes.cloud.api.dto.request.area.MarketDevelopmentUpdateRequest;
import com.mes.cloud.api.dto.response.area.MarketDevelopmentDto;
import com.mes.cloud.exception.BaseException;
import com.mes.cloud.common.CommPager;
import com.mes.cloud.common.JsonResult;
import com.mes.cloud.constant.Constants;
import com.mes.cloud.dao.BaseAreaMarketDevelopmentDao;
import com.mes.cloud.entity.BaseArea;
import com.mes.cloud.entity.BaseAreaMarketDevelopment;
import com.mes.cloud.entity.SysAreaLog;
import com.mes.cloud.entity.vo.area.MarketDevelopmentVo;
import com.mes.cloud.enums.HttpStatusEnum;
import com.mes.cloud.util.DateUtil;
import com.mes.cloud.util.UserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 区域市场发展
 *
 * @author dy
 * @version 2019-08-23 11:03:50
 * @email dongyi@shinho.net.cn
 */
@Service
public class BaseAreaMarketDevelopmentService {

    private BaseAreaMarketDevelopmentDao baseAreaMarketDevelopmentDao;

    private IPKeyGenerator iPKeyGenerator;

    private LogService logService;

    @Autowired
    public BaseAreaMarketDevelopmentService(BaseAreaMarketDevelopmentDao baseAreaMarketDevelopmentDao, IPKeyGenerator iPKeyGenerator, LogService logService) {
        this.baseAreaMarketDevelopmentDao = baseAreaMarketDevelopmentDao;
        this.iPKeyGenerator = iPKeyGenerator;
        this.logService = logService;
    }

    /**
     * 分页查列表
     *
     * @param pageRequest
     * @return JsonResult
     */
    public JsonResult<CommPager<MarketDevelopmentDto>> pageList(MarketDevelopmentPageRequest pageRequest) {
        Page<MarketDevelopmentDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        //查询条件
        Map<String, Object> params = new HashMap<>();
        params.put("areaId", pageRequest.getAreaId());
        params.put("queryString", pageRequest.getQueryString());
        List<MarketDevelopmentVo> baseAreaMarketDevelopmentList = baseAreaMarketDevelopmentDao.selectMarketDevelop(params);
        List<MarketDevelopmentDto> baseAreaMarketDevelopmentDtoList = new ArrayList<>();
        for (MarketDevelopmentVo baseAreaMarketDevelopment : baseAreaMarketDevelopmentList) {
            MarketDevelopmentDto baseAreaMarketDevelopmentDto = new MarketDevelopmentDto();
            BeanUtils.copyProperties(baseAreaMarketDevelopment, baseAreaMarketDevelopmentDto);
            // 判断是否失效
            String stage = baseAreaMarketDevelopmentDto.getStageTime();
            baseAreaMarketDevelopmentDto.setStatus(Constants.STATUS_UNEFFECTIVE);
            if (!StringUtils.isEmpty(stage)) {
                String[] splitStr = stage.split("~");
                String startDate = splitStr[0];
                String endDate = splitStr[1];
                String nowDate = DateUtil.getDateTime(DateUtil.DATE_FORMAT);
                if (DateUtil.compareDate(startDate, nowDate) <= 0 && DateUtil.compareDate(endDate, nowDate) >= 0) {
                    baseAreaMarketDevelopmentDto.setStatus(Constants.STATUS_EFFECTIVE);
                }
            }
            baseAreaMarketDevelopmentDtoList.add(baseAreaMarketDevelopmentDto);
        }
        CommPager<MarketDevelopmentDto> pageResult = new CommPager<>(page, baseAreaMarketDevelopmentDtoList);
        JsonResult<CommPager<MarketDevelopmentDto>> jsonResult = new JsonResult<>();
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(pageResult);
        return jsonResult;
    }

    /**
     * 新增
     *
     * @param marketDevelopmentRequest
     * @return JsonResult
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult add(MarketDevelopmentRequest marketDevelopmentRequest) {
        JsonResult jsonResult = new JsonResult();
        BaseAreaMarketDevelopment baseAreaMarketDevelopment = new BaseAreaMarketDevelopment();
        BeanUtils.copyProperties(marketDevelopmentRequest, baseAreaMarketDevelopment);

        // 查询该行政区划、该渠道下是否已定义市场发展阶段
        BaseAreaMarketDevelopment duplicate = new BaseAreaMarketDevelopment();
        duplicate.setAreaId(marketDevelopmentRequest.getAreaId());
        duplicate.setChannelId(marketDevelopmentRequest.getChannelId());
        duplicate.setStageDefinition(marketDevelopmentRequest.getStageDefinition());
        int bindCount = baseAreaMarketDevelopmentDao.selectCount(duplicate);
        if (bindCount > 0) {
            return jsonResult.setCode(HttpStatusEnum.REF_EXIST.getCode()).setMsg(HttpStatusEnum.REF_EXIST.getMessage());
        }

        baseAreaMarketDevelopment.setId(iPKeyGenerator.getGenerateKey());
        baseAreaMarketDevelopment.setUpdateDateStr(DateUtil.updateDateStr());
        baseAreaMarketDevelopment.setCreateBy(UserUtil.getCreateByName());
        baseAreaMarketDevelopment.setUpdateBy(UserUtil.getUpdateByName());
        baseAreaMarketDevelopment.setCreateByNo(UserUtil.getCreateByNo());
        baseAreaMarketDevelopment.setUpdateByNo(UserUtil.getUpdateByNo());
        int count = baseAreaMarketDevelopmentDao.insertSelective(baseAreaMarketDevelopment);
        if (count > 0) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode());
            // 插入操作日志
            BaseArea baseArea = new BaseArea();
            baseArea.setId(baseAreaMarketDevelopment.getAreaId());
            this.insertLog(baseArea, Constants.ADD_MARKET_DEVELOPMENT);
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(),HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    /**
     * 更新
     *
     * @param baseAreaMarketDevelopmentRequest
     * @return JsonResult
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult update(MarketDevelopmentUpdateRequest baseAreaMarketDevelopmentRequest) {
        JsonResult jsonResult = new JsonResult();
        BaseAreaMarketDevelopment duplicate = new BaseAreaMarketDevelopment();
        duplicate.setAreaId(baseAreaMarketDevelopmentRequest.getAreaId());
        duplicate.setChannelId(baseAreaMarketDevelopmentRequest.getChannelId());
        duplicate.setStageDefinition(baseAreaMarketDevelopmentRequest.getStageDefinition());
        BaseAreaMarketDevelopment baseAreaMarketDevelopment2 = baseAreaMarketDevelopmentDao.selectOne(duplicate);
        if (baseAreaMarketDevelopment2 != null  && !baseAreaMarketDevelopmentRequest.getId().equals(baseAreaMarketDevelopment2.getId())) {
            return jsonResult.setCode(HttpStatusEnum.REF_EXIST.getCode()).setMsg(HttpStatusEnum.REF_EXIST.getMessage());
        }
        BaseAreaMarketDevelopment baseAreaMarketDevelopment = new BaseAreaMarketDevelopment();
        BeanUtils.copyProperties(baseAreaMarketDevelopmentRequest, baseAreaMarketDevelopment);
        baseAreaMarketDevelopment.setUpdateDateStr(DateUtil.updateDateStr());
        baseAreaMarketDevelopment.setUpdateBy(UserUtil.getUpdateByName());
        baseAreaMarketDevelopment.setUpdateByNo(UserUtil.getUpdateByNo());
        int count = baseAreaMarketDevelopmentDao.updateByPrimaryKeySelective(baseAreaMarketDevelopment);

        if (count == 1) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage());
            jsonResult.setCode(HttpStatusEnum.OK.getCode());
            // 插入操作日志
            BaseArea baseArea = new BaseArea();
            baseArea.setId(baseAreaMarketDevelopmentRequest.getAreaId());
            this.insertLog(baseArea, Constants.UPDATE_MARKET_DEVELOPMENT);
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(),HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    /**
     * @description 查询市场发展详情
     * @author dongyi
     * @date 2019-08-05 16:41
     **/
    public JsonResult<MarketDevelopmentDto> get(String id) {
        JsonResult jsonResult = new JsonResult();
        //查询条件
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        MarketDevelopmentVo marketDevelopmentVo = baseAreaMarketDevelopmentDao.selectMarketDevelopDetail(params);
        if (marketDevelopmentVo != null) {
            MarketDevelopmentDto marketDevelopmentDto = new MarketDevelopmentDto();
            BeanUtils.copyProperties(marketDevelopmentVo, marketDevelopmentDto);

            // 判断是否失效
            String stage = marketDevelopmentDto.getStageTime();
            marketDevelopmentDto.setStatus(Constants.STATUS_UNEFFECTIVE);
            if (!StringUtils.isEmpty(stage)) {
                String[] splitStr = stage.split("~");
                String startDate = splitStr[0];
                String endDate = splitStr[1];
                String nowDate = DateUtil.getDateTime(DateUtil.DATE_FORMAT);
                if (DateUtil.compareDate(startDate, nowDate) <= 0 && DateUtil.compareDate(endDate, nowDate) >= 0) {
                    marketDevelopmentDto.setStatus(Constants.STATUS_EFFECTIVE);
                }
            }

            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(marketDevelopmentDto);
        } else {
            jsonResult.setMsg(HttpStatusEnum.RECORD_NOT_EXIST.getMessage()).setCode(HttpStatusEnum.RECORD_NOT_EXIST.getCode());
        }
        return jsonResult;
    }

    /**
     * @description 添加操作日志
     * @author dongyi
     * @date 2019-08-07 13:36
     **/
    private int insertLog(BaseArea baseArea, String logMessage) {
        SysAreaLog sysAreaLog = new SysAreaLog();
        sysAreaLog.setAreaId(baseArea.getId());
        sysAreaLog.setMenuCode(Constants.AREA_MENU_CODE);
        sysAreaLog.setLog(logMessage);
        sysAreaLog.setId(iPKeyGenerator.getGenerateKey());
        sysAreaLog.setUpdateDateStr(DateUtil.updateDateStr());
        sysAreaLog.setCreateBy(UserUtil.getCreateByName());
        sysAreaLog.setUpdateBy(UserUtil.getUpdateByName());
        sysAreaLog.setCreateByNo(UserUtil.getCreateByNo());
        sysAreaLog.setUpdateByNo(UserUtil.getUpdateByNo());
        return logService.insertAreaLog(sysAreaLog);
    }

    /**
     * 区域市场发展列表查询
     *
     * @param marketDevelopmentRequest
     * @return JsonResult<List<MarketDevelopmentDto>>
     */
    public JsonResult<List<MarketDevelopmentDto>> list(MarketDevelopmentRequest marketDevelopmentRequest) {
        JsonResult jsonResult = new JsonResult();
        //查询条件
        BaseAreaMarketDevelopment selectParam = new BaseAreaMarketDevelopment();
        BeanUtils.copyProperties(marketDevelopmentRequest, selectParam);
        List<BaseAreaMarketDevelopment> marketDevelopmentList = baseAreaMarketDevelopmentDao.select(selectParam);

        List<MarketDevelopmentDto> marketDevelopmentDtoList = new ArrayList<>();
        for (BaseAreaMarketDevelopment baseAreaMarketDevelopment : marketDevelopmentList) {
            MarketDevelopmentDto productDto = new MarketDevelopmentDto();
            BeanUtils.copyProperties(baseAreaMarketDevelopment, productDto);
            marketDevelopmentDtoList.add(productDto);
        }
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(marketDevelopmentDtoList);
        return jsonResult;
    }

    /**
     * 通过渠道id查询
     *
     * @param marketDevelopmentRequest
     * @return JsonResult<List<MarketDevelopmentDto>>
     */
    public JsonResult<List<MarketDevelopmentDto>> listByChannelIds(MarketDevelopmentRequest marketDevelopmentRequest) {
        //查询条件
        List<BaseAreaMarketDevelopment> marketDevelopmentList = baseAreaMarketDevelopmentDao.listByChannelIds(marketDevelopmentRequest);

        List<MarketDevelopmentDto> marketDevelopmentDtoList = new ArrayList<>();
        for (BaseAreaMarketDevelopment baseAreaMarketDevelopment : marketDevelopmentList) {
            MarketDevelopmentDto productDto = new MarketDevelopmentDto();
            BeanUtils.copyProperties(baseAreaMarketDevelopment, productDto);
            marketDevelopmentDtoList.add(productDto);
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(marketDevelopmentDtoList);
        return jsonResult;
    }


}
